/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import { PureComponent } from "react"
import ReactDOM from "react-dom"
import { PullToRefresh, ListView, Button, ActivityIndicator } from 'antd-mobile';
import getDataSource from "../MDatasource"
import { filterTemplate, isNull, goToPage, filterCalcField } from "../../utils/helper"
import BackTop from "../BackTop/BackTop"
import MAction from "../MAction/MAction"
import { connect } from "dva";
@connect(({ global }, { formDataKey }) => {
	return ({
		rowApiKeys: global.listviewRowApiKeys[formDataKey]
	})
})
export default class App extends PureComponent {
	constructor(props) {
		super(props);
		this.lvTimeOut = null;
		const getRowData = (dataBlob, sectionID, rowID) => {
			return dataBlob[sectionID][rowID]
		};
		const dataSource = new ListView.DataSource({
			getRowData,
			rowHasChanged: (row1, row2) => {
				return row1 !== row2;
			},
		});
		let { use_body_scroll } = props;
		let useBodyScroll = isNull(use_body_scroll) || use_body_scroll === 0 || use_body_scroll === "0";
		this.state = {
			dataSource,
			refreshing: true,
			isLoading: true,
			height: document.documentElement.clientHeight,
			useBodyScroll: !useBodyScroll,
			pagesize: 20,
			pageindex: 1,
			hasMore: true,
			loading: false,
			open: false
		};
	}
	onOpenChange = () => {
		this.setState({
			open: !this.state.open
		})
	}
	// If you use redux, the data maybe at props, you need use `componentWillReceiveProps`
	// componentWillReceiveProps(nextProps) {
	//   if (nextProps.dataSource !== this.props.dataSource) {
	//     this.setState({
	//       dataSource: this.state.dataSource.cloneWithRows(nextProps.dataSource),
	//     });
	//   }
	// }
	componentWillMount() {
		if (browser.isInApp) {
			Func.registerHanderBridge("callbackCloseWindow", this.changeData);
		}
		let { page_size } = this.props;
		if (isNull(page_size)) {
			page_size = 20;
		}
		this.setState({
			pagesize: page_size
		})
	}

	componentWillReceiveProps(next) {
		let oldFD = this.props.fd.formData;
		let { fd: { config }, dataset_key } = this.props;
		let { datasets } = config;
		let newFD = next.fd.formData;
		if (!_.isEqual(oldFD, newFD)) {
			let { _random: oldRandom } = oldFD;
			let { _random: newRandom } = newFD;
			// 高级搜索-- 点击搜索时 和 点击弹窗里面的搜索时 改变随机数 触发搜索,不论data_store有没有改变都会触发
			let ds = datasets[dataset_key];
			let isSearch = false;
			if (!isNull(ds)) {
				try {
					if (this.watchStr(ds.api.params, oldFD, newFD) || (oldRandom !== newRandom)) {
						isSearch = true
					}
				} catch (e) {
				}
			}
			if (isSearch) {
				let { pagesize } = this.state;
				this.setState({
					loading: true
				})
				try {
					this.lv.scrollTo(0)
				}
				catch (e) {

				}
				getDataSource({
					...next, pager: { pagesize, pageindex: 1 }, callback: (data) => {
						let list = data[0].list || [];
						// let list = data;
						this.rData = list;
						this.setState({
							dataSource: this.state.dataSource.cloneWithRows(this.rData),
							refreshing: false,
							isLoading: false,
							pageindex: 1,
							loading: false
						});
					}
				})
			}
		}
		if (browser.isInApp) {
			let { rowApiKeys: oldRowApiKeys } = this.props;
			let { rowApiKeys: newRowApiKeys } = next;
			if (!_.isEqual(oldRowApiKeys, newRowApiKeys)) {
				Func.registerHanderBridge("callbackCloseWindow", this.changeData)
			}
			let { isChangeRefreshing: oldIsChangeRefreshing } = this.props;
			let { isChangeRefreshing: newIsChangeRefreshing } = next;

			if (oldIsChangeRefreshing !== newIsChangeRefreshing) {//修改form中，didMount时 isShowFooterButton为false，然后再为true，所以需要监听参数的变化
				this.onRefresh()
			}
		}

	}
	componentDidUpdate() {
		if (this.state.useBodyScroll) {
			document.body.style.overflow = 'auto';
		} else {
			document.body.style.overflow = 'hidden';
			document.getElementById("root").style.overflow = 'hidden';
		}
	}
	watchStr(arr, oldFD = {}, newFD = {}) {
		let oldStr = "", newStr = "";
		if (!arr || arr.length == 0) {

		}
		else {
			arr.map(item => {
				oldStr += "," + oldFD[item.store_field || item.key];
				newStr += "," + newFD[item.store_field || item.key];
			});
		}
		return oldStr !== newStr
	}
	componentDidMount() {
		let { isShowFooterButton } = this.props;
		let { pagesize } = this.state;
		let hei = this.state.height - ReactDOM.findDOMNode(this.lv).getBoundingClientRect().top;
		if (isShowFooterButton) {
			hei = hei - 45;
		}
		getDataSource({
			...this.props, pager: { pagesize, pageindex: 1 }, callback: (data) => {
				let list = data[0].list || [];
				// let list = data;
				this.rData = list;
				this.setState({
					dataSource: this.state.dataSource.cloneWithRows(list),
					height: hei,
					refreshing: false,
					isLoading: false,
					// isLoading: list.length<pagesize,
					// hasMore: list.length>=pagesize,
					pageindex: 1
				});
			}
		})
		this.lvTimeOut = setTimeout(() => {
			let height = document.documentElement.clientHeight
			let hei = height - ReactDOM.findDOMNode(this.lv).getBoundingClientRect().top;
			let { isShowFooterButton } = this.props;
			if (isShowFooterButton) {
				hei = hei - 45;
			}
			this.setState({
				height: hei
			})
		}, 2000)
	}

	onRefresh = () => {
		this.setState({ refreshing: true, isLoading: true });
		// simulate initial Ajax
		let { pagesize } = this.state;
		getDataSource({
			...this.props, pager: { pagesize, pageindex: 1 }, callback: (data) => {
				let list = data[0].list || [];
				// let list = data;
				this.rData = list;
				setTimeout(() => {
					this.setState({
						dataSource: this.state.dataSource.cloneWithRows(this.rData),
						refreshing: false,
						isLoading: false,
						pageindex: 1
					});
				}, 1000)
			}
		})
	};

	onEndReached = (event) => {
		// load new data
		// hasMore: from backend data, indicates whether it is the last page, here is false
		if (this.state.isLoading && !this.state.hasMore) {
			return;
		}
		// console.log('reach end', event);
		this.setState({ isLoading: true });
		let { pageindex, pagesize } = this.state;
		getDataSource({
			...this.props, pager: { pagesize, pageindex: pageindex + 1 }, callback: (data) => {
				let list = data[0].list || [];
				// let list = data;
				if (list.length < pagesize) {
					this.rData = [...this.rData, ...list];
					this.setState({
						dataSource: this.state.dataSource.cloneWithRows(this.rData),
						isLoading: true,
						pageindex: pageindex + 1,
						hasMore: false
					});
				}
				else {
					this.rData = [...this.rData, ...list];
					this.setState({
						dataSource: this.state.dataSource.cloneWithRows(this.rData),
						isLoading: false,
						pageindex: pageindex + 1
					});
				}
			}
		})
	};
	// 由列表中打开页面，比如修改页 然后从修改页返回时刷新当前这一条数据
	changeData = () => {
		let { rowApiKeys: obj } = this.props;
		let { apiInfo, data } = obj;
		let { dispatch } = this.props;
		dispatch({
			type: "form/query",
			payload: {
				apiInfo,
				data,
				callback: (result) => {
					let { data } = result;
					let { id } = data;
					if (!isNull(id)) {
						let newList = [];
						this.rData.map((item, key) => {
							if (item.id === id) {
								newList.push({ ...data })
							}
							else {
								newList.push({ ...item })
							}
						})
						//不能直接修改this.rData 否则页面不会刷新 
						this.setState({
							dataSource: this.state.dataSource.cloneWithRows(newList)
						})
						setTimeout(() => {
							this.rData = newList;
						})
					}

				}
			}
		})
	}
	row = (rowData, sectionID, rowID) => {
		let item = rowData;
		let { formData, use_onclick, template, templates, calc_field } = this.props;
		if (!isNull(calc_field)) {
			item = filterCalcField(item, calc_field);
		}
		let str = template;
		// use_onclick 用模板上的 onclick  不对整行点击
		if (!isNull(templates) && Object.keys(templates).length > 0) {
			/*
			如果是多个模板，根据条件使用不同的模板
			配置了templates时使用，否则还是使用template
			templates:{
				"item.type==1":"",
				"item.type==2":""
			}
			*/
			for (let condition in templates) {
				let t = templates[condition];
				if (eval(condition)) {
					str = t;
				}
			}
		}
		else {
			str = template;
		}
		return (
			<div key={rowID} dangerouslySetInnerHTML={{ __html: filterTemplate(str, item) }} onClick={() => {
				if (use_onclick == 1) {
					return;
				}
				else {
					let { event_key } = item;
					MAction({ ...this.props, formData: { ...formData, ...rowData } }, event_key || this.props.event_key)
				}
			}}>
			</div>
		)
	}
	render() {
		let { template, dataset_key, dispatch, id, separator_style, use_onclick } = this.props;
		let { hasMore, loading, dataSource, refreshing, pagesize } = this.state;
		// let loading=this.props.fd[dataset_key+"Loading"]
		const separator = (sectionID, rowID) => (
			<div
				key={`${sectionID}-${rowID}`}
				className="separator"
				style={{
					...separator_style
				}}
			/>
		);
		window._MAction = (event_key, key, oid) => {
			if (use_onclick == 1) {
				// onclick='_MAction(\"go_zl_xf\",\"id\",{{id}})'
				let { formData } = this.props;
				let rowData = this.rData.filter(i => i[key] == oid)[0];
				MAction({ ...this.props, formData: { ...formData, ...rowData } }, event_key)
			}
		};

		return (
			<div className="mi-listview" id={"listview_" + id}>
				<ActivityIndicator toast text="正在加载" animating={loading || refreshing} className={refreshing ? "refreshing" : ""} />
				<BackTop dom={this.lv} />
				<ListView
					onScroll={(e) => {
						{/*console.log(e.target.scrollTop);*/ }
					}}
					pageSize={5}
					initialListSize={pagesize}
					key={this.state.useBodyScroll ? '0' : '1'}
					ref={el => this.lv = el}
					dataSource={dataSource}
					renderFooter={() => {
						if (hasMore) {
							if (dataSource.rowIdentities.length == 0 || dataSource.rowIdentities[0].length == 0) {
								return (
									<div style={{ padding: "30px 30px 100px 30px", textAlign: 'center' }}>
										{
											this.state.isLoading ? '加载中...' : '暂无数据'
										}
									</div>
								)
							}
							return (<div style={{ padding: 30, textAlign: 'center' }}>
								{this.state.isLoading ? '加载中...' : ''}
							</div>)
						}
						else {
							return null
						}
					}}
					renderRow={this.row}
					renderSeparator={separator}
					useBodyScroll={this.state.useBodyScroll}
					className={this.state.useBodyScroll ? "use-body-scroll" : ""}
					style={this.state.useBodyScroll ? {} : {
						height: this.state.height,
						border: '1px solid #ddd',
						margin: '5px 0',
					}}
					pullToRefresh={
						<PullToRefresh
							refreshing={this.state.refreshing}
							onRefresh={this.onRefresh}
							distanceToRefresh={50}
							indicator={{
								// deactivate: <div>下拉可以刷新</div>,
								// activate: "松开立即刷新",
								// release: "正在刷新数据中...",
								// release:<ActivityIndicator size="large"/>,
								// finish: "刷新完成"
							}}
						/>}
					onEndReached={this.onEndReached}
					onEndReachedThreshold={50}
				/>
			</div>);
	}


	componentWillUnmount() {
		clearTimeout(this.lvTimeOut)
		document.body.style.overflow = 'auto';
		document.getElementById("root").style.overflow = 'auto';
		let { dispatch, formDataKey } = this.props;
		dispatch({
			type: "global/removeListviewRowApiKey",
			payload: {
				key: formDataKey
			}
		})
	}
}